package org.jeecg.modules.flow.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.flow.entity.FlowProcessBusiness;
import org.jeecg.modules.flow.mapper.FlowProcessBusinessMapper;
import org.jeecg.modules.flow.service.IFlowProcessBusinessService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Description: 流程匹配功能实现类
 * @Author: jeecg-boot
 * @Date: 2021-11-22
 * @Version: V1.0
 */
@Service
@Slf4j
public class FlowProcessBusinessServiceImpl extends ServiceImpl<FlowProcessBusinessMapper, FlowProcessBusiness> implements IFlowProcessBusinessService {

    @Resource
    private ISysBaseAPI sysBaseAPI;

    /**
     * 匹配流程
     *
     * @param cusNo        核心企业号
     * @param orgId        发起用户的机构号
     * @param businessType 业务类型
     * @return
     */
    @Override
    public String matchProcess(Integer cusNo, String orgId, String businessType) {
        String processId = "";
        if (StringUtils.isBlank(orgId) && cusNo == null || StringUtils.isBlank(businessType)) {
            return processId;
        }
        List<FlowProcessBusiness> processList = lambdaQuery().select(FlowProcessBusiness::getProcessId)
                .eq(cusNo != null, FlowProcessBusiness::getCusNo, cusNo)
                .eq(FlowProcessBusiness::getBusinessType, businessType)
                .eq(StringUtils.isNotBlank(orgId), FlowProcessBusiness::getOrgId, orgId)
                .orderByDesc(FlowProcessBusiness::getVersion)
                .list();

        if (CollectionUtils.isNotEmpty(processList)) {
            processId = processList.get(0).getProcessId();
        } else { // 当前机构下没有匹配到流程则根据上级机构去获取
            Result<Map<String, List<String>>> mapResult = sysBaseAPI.queryParentIdsById(orgId);
            if (mapResult.isSuccess() && !mapResult.getResult().isEmpty() && !mapResult.getResult().get(orgId).isEmpty()) {
                List<FlowProcessBusiness> list = lambdaQuery().select(FlowProcessBusiness::getProcessId)
                        .eq(cusNo != null, FlowProcessBusiness::getCusNo, cusNo)
                        .eq(FlowProcessBusiness::getBusinessType, businessType)
                        .in(FlowProcessBusiness::getOrgId, mapResult.getResult().get(orgId))
                        .orderByDesc(FlowProcessBusiness::getVersion)
                        .list();
                if (CollectionUtils.isNotEmpty(list)) {
                    processId = list.get(0).getProcessId();
                }
            }
        }
        log.info("流程匹配,核心企业号：{}，机构号：{}，业务类型：{},匹配流程：{}", cusNo, orgId, businessType, processId);
        return processId;
    }
}
